const oSliderPage = document.querySelector('.slider-page'),
  oScrollWrapper = oSliderPage.querySelector('.scroll-wrapper'),
  oSliderItems = oScrollWrapper.querySelectorAll('.slider-item'),
  pageWidth = oSliderPage.offsetWidth;

let startX = 0,
  pageIndex = 0,
  distanceX = 0,
  isMove = false;

const init = () => {
  bindEvent();
};

function bindEvent() {
  oScrollWrapper.addEventListener('touchstart', handlerTouchStart, false);
  oScrollWrapper.addEventListener('touchmove', handlerTouchMove, false);
  oScrollWrapper.addEventListener('touchend', handlerTouchEnd, false);
}

function handlerTouchStart(e) {
  startX = e.touches[0].clientX;
  console.log(startX);
}

function handlerTouchMove(e) {
  const moveX = e.touches[0].clientX;

  //第一页不能右滑动 最后一页不能左滑动
  if (
    (moveX > startX && pageIndex === 0) ||
    (moveX < startX && pageIndex === oSliderItems.length - 1)
  ) {
    return;
  }

  //滑动距离
  distanceX = moveX - startX;

  //滑动距离动画
  setTranslateX(-pageWidth * pageIndex + distanceX);

  isMove = true;
}

function handlerTouchEnd() {
  if (isMove) {
    //移动距离大于1/3时
    if (Math.abs(distanceX) > +pageWidth / 3) {
      //右滑动
      if (distanceX > 0) {
        pageIndex--;
      }

      //左滑动
      if (distanceX < 0) {
        pageIndex++;
      }
    }

    //切换
    setTranslateX(-pageIndex * pageWidth);
  }

  //回弹
  startX = 0;
  distanceX = 0;
  isMove = false;
}

function setTranslateX(tranX) {
  oScrollWrapper.style.transition = 'all .1s';
  oScrollWrapper.style.transform = `translateX(${tranX}px)`;
}

init();
